<template>
  <div class="box">
    <div class="inp">
      <span class="search-icon"></span>
      <input
        type="text"
        id="search"
        v-model="input"
        placeholder="搜索"
        @input="debouncedHandleSearch"
        autocomplete="off"
      />
      <span class="clear-icon" @click.self="clearInput"></span>
    </div>
    <div class="search-content">
      <template v-if="poiData.length > 0">
        <div
          class="search-item"
          v-for="item in poiData"
          :key="item"
          :title=" item.distance + '公里'"
          @click="toView(item)"
        >
          <span class="poi-icon"></span>
          <span class="poi-text">{{ item.name }}</span>
          <span class="poi-distance"> 【{{ item.distance + '公里' }}】</span>
        </div>
      </template>

      <div v-else>暂无数据</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onUnmounted } from 'vue'
import { createPoint, computedDistance } from '../../../api/gis2d/maputils'
import { useMapStoreStore } from '../../../stores/index'
import useDebounce from '../../../hook/useDebounce'
import { transformExtent } from 'ol/proj'
import { ElMessage } from 'element-plus'
import config from '../../../config'

const store = useMapStoreStore()
const input = ref('')
const poiData = ref([])
let vectorLayer = null
let edit = null
let del = null

const clearInput = () => {
  input.value = ''
  poiData.value = [];
  vectorLayer = null;
   del && del()
}

// 获取当前地图视野的边界
function getViewBounds() {
  const view = map.getView()
  const extent = view.calculateExtent(map.getSize())
  return transformExtent(extent, view.getProjection(), 'EPSG:4326')
}

const getTdtPoi = () => {
  if (input.value === '') {
    poiData.value = []
    return
  }
  const bounds = getViewBounds()
  const boundsStr = bounds.join(',')
  const apiUrl = `http://api.tianditu.gov.cn/v2/search?postStr={"keyWord":"${input.value}","level":${Math.min(Math.floor(map.getView().getZoom()),18)},"mapBound":"${boundsStr}","queryType":2,"start":0,"count":40}&type=query&tk=${config.TDTTK}`
  fetch(apiUrl)
    .then((response) => response.json())
    .then((data) => {
      if (data && data.pois && data.pois.length > 0) {
        var center = store.center
        data.pois.forEach((d, i, t) => {
          var poi = d.lonlat.split(',')
          t[i].distance = computedDistance(
            [Number(poi[0]), Number(poi[1])],
            [store.earthquakeInfo.longitude, store.earthquakeInfo.latitude]
          )
        })

        poiData.value = data.pois
      } else {
        ElMessage({
          message: '暂无数据',
          type: 'warning',
          plain: true
        })

        poiData.value = []
      }
    })
    .catch((error) => {
      ElMessage({
        message: error,
        type: 'error',
        plain: true
      })
    })
}

const toView = (e) => {
  const [longitude, latitude] = e.lonlat.split(',')
  const coordinates = [Number(longitude), Number(latitude)]
  if (vectorLayer) {
    edit({ poi: coordinates, data: e })
    return
  }
  ;({
    vectorLayer: vectorLayer,
    edit: edit,
    del: del
  } = createPoint({ poi: coordinates, data: e, type: 'search-poi' }))
}
const debouncedHandleSearch = useDebounce(getTdtPoi, 1000)

onUnmounted(() => {
  del && del()
})
</script>

<style lang="scss" scoped>
.box {
  height: 100%;
  padding: 46px 10px 20px;
  font-size: 20px;
  color: #b9eeff;
  .inp {
    position: relative;
    .search-icon {
      display: inline-block;
      width: 20px;
      height: 20px;
      background-image: url(/static/icon/搜索@1x.png);
      background-size: contain;
      position: absolute;
      left: 10px;
      top: 10px;
    }
    .clear-icon {
      display: inline-block;
      width: 20px;
      height: 20px;
      background-image: url(/static/icon/删除@1x.png);
      background-size: contain;
      position: absolute;
      right: 10px;
      top: 10px;
      cursor: pointer;
    }
    .clear-icon:hover {
      transform: rotate(360deg);
      transition: all 1s ease;
    }
    #search {
      width: 100%;
      padding: 0 35px;
      height: 40px;
      background: rgba(0, 25, 51, 0.8);
      border-radius: 4px;
      border: none;
      outline: none;
      color: #b9eeff;
      font-size: 16px;
      box-sizing: border-box;
      &::placeholder {
        color: #b9eeff;
      }
    }
  }

  .search-content {
      height: calc(100% - 120px);
    margin-top: 20px;
    overflow-y: auto;
    box-sizing: border-box;
    // 滚动条整体部分
    &::-webkit-scrollbar {
      width: 6px;
      height: 8px;
    }
    &::-webkit-scrollbar-button {
      display: none;
    }
    &::-webkit-scrollbar-thumb {
      background: #01c2ff;
      cursor: pointer;
      border-radius: 4px;
    }
    &::-webkit-scrollbar-corner {
      display: none;
    }
    &::-webkit-resizer {
      display: none;
    }
    .search-item {
      width: 100%;
      min-height: 40px;
      padding: 0 5px;
      box-sizing: border-box;
      border-bottom: 1px solid #01c2ff;
      font-size: 16px;
      line-height: 40px;

      cursor: pointer;
      display: flex;
      align-items: center;
      span {
        display: inline-block;
      }
      .poi-text {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin-left: 15px;
      }
      .poi-distance {
        width: 75px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .poi-icon {
        width: 32px;
        height: 32px;
        background-image: url(/static/icon/poi.png);
        background-size: 100% 100%;
      }
    }
    .search-item:hover {
      background-color: #2eaacf80;
    }
  }
}
</style>